<template>
  <view class="form-content safety-edit">
    <u-form
      :model="form"
      ref="refForm"
      label-position="top"
      :error-type="['toast']"
    >
      <u-form-item label="手机号" prop="mobile" :required="true">
        <view class="gary-bg">
          <u-input v-model="form.mobile" :disabled="true" />
        </view>
      </u-form-item>
      <u-form-item label="新密码" prop="signPassword" :required="true">
        <view class="white-bg">
          <u-input
            v-model="form.signPassword"
            type="password"
            :password-icon="true"
            @input="changePassword($event)"
          />
        </view>
        <view class="bg-transparent" v-if="form.signPassword !== undefined && form.signPassword !== null && actionType === 1">
          <view v-for="item in strategyMsg" :class="[item.flag?'success':'error','error-msg']">
            <u-icon name="checkmark-circle" class="success" size="28" v-if="item.flag"></u-icon>
            <u-icon name="close-circle" class="error" size="28" v-if="!item.flag"></u-icon>
            {{ item.msgContent }}
          </view>
          <view class="error error-msg" v-if="!form.signPassword">请输入密码</view>
        </view>
      </u-form-item>
      <u-form-item label="确认新密码" prop="signPassword2" :required="true">
        <view class="white-bg">
          <u-input
            v-model="form.signPassword2"
            type="password"
            :password-icon="true"
          />
        </view>
      </u-form-item>
    </u-form>
  </view>
  <view class="btn-box">
    <u-button shape="circle" type="primary" plain @click="submit"
      >保存</u-button
    >
  </view>
</template>
<script lang="ts" setup>
import { useUserStoreWidthOut } from '@/stores/user';
import { nextTick } from 'vue';
import {
  setSignPassword,
  setPassword,
  queryStrategy,
} from '@/api/modules/user';
import { onLoad, onReady } from '@dcloudio/uni-app';
import md5 from 'md5';

const asyncUser = useUserStoreWidthOut();
const userInfo: any = asyncUser.getUserInfo;

const form = ref<any>({
  signPassword: undefined,
  signPassword2: '',
  password: '',
  userId: userInfo.userId,
  code: '1',
});

const rules = {
  signPassword: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur,change',
    },
  ],
  signPassword2: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur,change',
    },
  ],
};

const cellClick = () => {
  (uni as any).$Router.replace({
    name: 'login',
  });
};
const refForm = ref();
const submit = async () => {
  if (actionType.value === 2) {
    // 签名密码只需要校验长度大于等于6位
    if (form.value.signPassword.length < 6) {
      uni.showToast({
        title: '签名密码长度必须大于或等于6位',
        icon: 'none',
        duration: 2000,
      });
      return;
    }
  } else {
    // 登录密码校验
    validatePassword(form.value.signPassword);
    for (const temp of strategyMsg.value) {
      if (!temp.flag) {
        uni.showToast({
          title: temp.msgContent,
          icon: 'none',
          duration: 2000,
        });
        return;
      }
    }
  }
  if (form.value.signPassword !== form.value.signPassword2) {
    uni.showToast({
      title: '确认密码不一致，请检查',
      icon: 'none',
      duration: 2000,
    });
    return;
  }
  const subForm = JSON.parse(JSON.stringify(form.value));
  if (actionType.value === 1) {
    subForm.password = md5(subForm.signPassword);
    subForm.signPassword = '';
  } else {
    subForm.signPassword = md5(subForm.signPassword);
  }
  subForm.signPassword2 = '';
  const fn = actionType.value === 1 ? setPassword : setSignPassword;
  fn(subForm).then(() => {
    cellClick();
  });
};
// 获取安全策略
const strategy = ref<any>({});
const strategyMsg = ref<any>([]);
const getStrategy = () => {
  const query = {
    checkType: 1,
    userId: userInfo.userId,
  };
  queryStrategy(query).then((res: any) => {
    strategy.value = res;
    if (res.minimumLength) {
      strategyMsg.value.push({
        msgId: 1,
        msgContent: '密码长度请不低于' + res.minimumLength + '位',
        flag: false,
      });
    }
    if (res.includeDigits) {
      strategyMsg.value.push({
        msgId: 2,
        msgContent: '请包含数字',
        flag: false,
      });
    }
    if (res.includeUppercase) {
      strategyMsg.value.push({
        msgId: 3,
        msgContent: '请包含大写字母',
        flag: false,
      });
    }
    if (res.includeLowercase) {
      strategyMsg.value.push({
        msgId: 4,
        msgContent: '请包含小写字母',
        flag: false,
      });
    }
    if (res.includeCharacters) {
      strategyMsg.value.push({
        msgId: 5,
        msgContent: '请包含特殊字符',
        flag: false,
      });
    }
  });
};

getStrategy();

// 校验密码
const validatePassword = (e: string) => {
  if (e.length >= strategy.value.minimumLength) {
    strategyMsg.value.forEach((item: any) => {
      if (item.msgId === 1) {
        item.flag = true;
      }
    });
  } else {
    strategyMsg.value.forEach((item: any) => {
      if (item.msgId === 1) {
        item.flag = false;
      }
    });
  }
  if (/[0-9]/.test(e)) {
    strategyMsg.value.forEach((item: any) => {
      if (item.msgId === 2) {
        item.flag = true;
      }
    });
  } else {
    strategyMsg.value.forEach((item: any) => {
      if (item.msgId === 2) {
        item.flag = false;
      }
    });
  }
  if (/[A-Z]/.test(e)) {
    strategyMsg.value.forEach((item: any) => {
      if (item.msgId === 3) {
        item.flag = true;
      }
    });
  } else {
    strategyMsg.value.forEach((item: any) => {
      if (item.msgId === 3) {
        item.flag = false;
      }
    });
  }
  if (/[a-z]/.test(e)) {
    strategyMsg.value.forEach((item: any) => {
      if (item.msgId === 4) {
        item.flag = true;
      }
    });
  } else {
    strategyMsg.value.forEach((item: any) => {
      if (item.msgId === 4) {
        item.flag = false;
      }
    });
  }
  if (/[^A-Za-z0-9]/.test(e)) {
    strategyMsg.value.forEach((item: any) => {
      if (item.msgId === 5) {
        item.flag = true;
      }
    });
  } else {
    strategyMsg.value.forEach((item: any) => {
      if (item.msgId === 5) {
        item.flag = false;
      }
    });
  }
};
const changePassword = (e:any) => {
  validatePassword(e)
}
const currTitle = ref<string>('');
const actionType = ref<number>(0);
onLoad(() => {
  const { type, title } = (uni as any).$Router.getQuery();
  currTitle.value = title;
  actionType.value = type;
  form.value.mobile = userInfo.mobile;
  uni.setNavigationBarTitle({
    title,
  });
});
onReady(() => {
  refForm.value.setRules(rules);
});
</script>
<style lang="scss">
page {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  position: relative;
  padding-bottom: env(safe-area-inset-bottom);
}
.btn-box {
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
}
.form-content {
  padding: 32rpx;
  padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);
  .white-bg {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 0 0 0 20rpx;

    .u-input__right-icon {
      .u-icon__icon {
        font-size: 40rpx !important;
      }
    }
  }
  .gary-bg {
    background-color: #e6e6e6;
    border-radius: 16rpx;
    padding: 0 20rpx;
  }
  .bg-transparent {
    background-color: transparent;
    padding-top: 10rpx;
  }
  .error-msg {
    line-height: normal;
  }
}
.safety-edit {
  .uicon-eye,
  .uicon-eye-fill {
    padding: 20rpx;
  }
}
</style>
